

----------------安装tf卡和u盘插件----------------
function install_gamesd(mode, sel)

	ProgressDialog(NOW_EXECUTING, "", 0, nil)
	lock_home_key()
	
	local storagemgrSrcPath = "resources/mc_plugins/storagemgr.skprx"
	local gamesdUmaSrcPath = "resources/mc_plugins/gcd-uma0/gamesd.skprx" 
	local gamesdUxSrcPath = "resources/mc_plugins/gcd-ux0/gamesd.skprx" 
	local usbmcSrcPath = "resources/mc_plugins/uma-ux0/usbmc.skprx" 
	local usbmc2SrcPath = "resources/mc_plugins/uma-ux0_gcd-uma0/usbmc.skprx" 
 
	local storagemgrName = "storagemgr.skprx"
	local gamesdName = "gamesd.skprx"
	local usbmcName = "usbmc.skprx"

	local storagemgrDstPath = "ur0:tai/"..storagemgrName
	local gamesdDstPath = "ur0:tai/"..gamesdName
	local usbmcDstPath = "ur0:tai/"..usbmcName
 
	local storagemgrGamesdUmaValue = {
		"MCD=ux0",
		"GCD=uma0",
		"INT=imc0",
	}
	local storagemgrGamesdUxValue = {
		"GCD=ux0",
		"MCD=uma0",
		"INT=imc0",
	}
	local storagemgrUsbUxValue = {
		"UMA=ux0",
		"MCD=uma0",
		"INT=imc0",
	}
	local storagemgrUsbUx2Value = {
		"UMA=ux0",
		"GCD=uma0",
		"MCD=xmc0",
		"INT=imc0",
	}
	local storagemgrValue = storagemgrGamesdUmaValue
	local storagemgrConfigPath = "ur0:/tai/storage_config.txt"
	local storagemgrLogPath = "ur0:/tai/storagemgr_log.txt"
 
	local prxSrcPath = storagemgrSrcPath
	local prxDstPath = storagemgrDstPath
 
	--判断选择哪个插件
	if mode == 1 then
		if sel == 1 then
			prxSrcPath = gamesdUmaSrcPath
			prxDstPath = gamesdDstPath
		elseif sel == 2 then
			prxSrcPath = gamesdUxSrcPath
			prxDstPath = gamesdDstPath
		elseif sel == 3 then
			prxSrcPath = usbmcSrcPath
			prxDstPath = usbmcDstPath		
		elseif sel == 4 then
			prxSrcPath = usbmc2SrcPath
			prxDstPath = usbmcDstPath		
		end
	elseif mode == 2 then
		if sel == 1 then
			storagemgrValue = storagemgrGamesdUmaValue
		elseif sel == 2 then
			storagemgrValue = storagemgrGamesdUxValue
		elseif sel == 3 then
			storagemgrValue = storagemgrUsbUxValue	
		elseif sel == 4 then
			storagemgrValue = storagemgrUsbUx2Value	
		end
	end
 
	--修改config.txt文件
  local partitionList = {"ux0:", "uma0:", "imc0:", "xmc0:"}
	for i = 1, #partitionList do
		local partitionPath = partitionList[i]
		local configPath = partitionPath.."/tai/config.txt"
		local configExist = checkFileExist(configPath)
		if configExist then
			if partitionPath == "ux0:" then
				copyPath(configPath, "ur0:/tai/")
			end
			local configBakPath = configPath..".bak"
			deletePath(configBakPath)
			copyFile(configPath, configBakPath)
		end
		deletePath(configPath)
		createFolder(configPath)
	end
	
	ProgressDialog(NOW_EXECUTING, "", 50, nil)

	local completed = true
	local configPath = "ur0:/tai/config.txt"
	local configExist = checkFileExist(configPath)
	while true do
		if not configExist then
			deletePath(configPath)
			if createFile(configPath) < 0 then
				completed = false
				break
			end
		else
			copyFile(configPath, configPath..".bak") --备份config.txt
		end

		local contenido = {}
		local section = "*KERNEL"
		local getSection = false
		local getInsertNum = false
		local insertNum = -1

		local input = io.open(configPath, "r")
		if input == nil then
			completed = false
			break
		end
		for linea in input:lines() do
			local mLinea = trimString(linea)
			local lineName = getFileName(mLinea)
			local lineNameLow = string.lower(lineName)
			if lineNameLow ~= string.lower(storagemgrName) and lineNameLow ~= string.lower(gamesdName) and lineNameLow ~= string.lower(usbmcName) then
				table.insert(contenido, linea)
				if not getInsertNum then
					if not getSection then
						if mLinea == section then
							insertNum = #contenido+1
							getSection = true
						end
					else
					 local firstChar = string.sub(mLinea, 1, 1)
						if firstChar == "*" then
							getInsertNum = true
						elseif firstChar == "#" then
						 insertNum = insertNum+1
						end
					end --if not getSection
				end --if not getInsertNum
			end --if lineNameLow
		end --for linea in
		
		if getSection then
			table.insert(contenido, insertNum, prxDstPath)
		else --如果找不到KERNEL则添加
			table.insert(contenido, section)
			table.insert(contenido, prxDstPath)
		end
		--写入文本
		if writeLines(configPath, contenido)	~= 1 then
			completed = false
			break
		end
		
		--删除旧插件
		deletePath(storagemgrDstPath)
		deletePath(storagemgrConfigPath)
		deletePath(storagemgrLogPath)
		deletePath(gamesdDstPath)
		deletePath(usbmcDstPath)
		--复制新插件
		if files.copy(prxSrcPath, "ur0:tai/") ~= 1 then
			completed = false
			break
		end
		--写入插件配置文件
		if mode == 2 then
			if writeLines(storagemgrConfigPath, storagemgrValue) < 0 then
				completed = false
				break
			end
		end
		break
	end
	
	unlock_home_key()
	ProgressDialog(NOW_EXECUTING, "", 100, nil)
	dismissDialog()
	
	--如果安装失败则返回
	if not completed then
		return -1
	end
  
  return 1

end

----------------卸载tf卡和u盘插件----------------
function uninstall_gamesd(sel)

	ProgressDialog(NOW_EXECUTING, "", 0, nil)
	lock_home_key()

	local storagemgrName = "storagemgr.skprx"
	local gamesdName = "gamesd.skprx"
	local usbmcName = "usbmc.skprx"

	local storagemgrDstPath = "ur0:tai/"..storagemgrName
	local gamesdDstPath = "ur0:tai/"..gamesdName
	local usbmcDstPath = "ur0:tai/"..usbmcName
 
	local storagemgrConfigPath = "ur0:/tai/storage_config.txt"
	local storagemgrLogPath = "ur0:/tai/storagemgr_log.txt"
    
    local prxName = storagemgrName
    if sel == 2 then
        prxName = gamesdName
    elseif sel == 3 then
        prxName = usbmcName
    end
	--修改config.txt文件
	local partitionList = {"ux0:", "ur0:", "uma0:", "imc0:", "xmc0:"}
	for i = 1, #partitionList do
		local partitionPath = partitionList[i]
		local configPath = partitionPath.."/tai/config.txt"
		local configExist = checkFileExist(configPath)
		if configExist then
			copyFile(configPath, configPath..".bak") --备份config.txt
			--读取文本
			local contenido = {}
			for linea in io.lines(configPath) do
				local mLinea = trimString(linea)
				local lineName = getFileName(mLinea)
				local lineNameLow = string.lower(lineName)
				if lineNameLow ~= string.lower(prxName) then
					table.insert(contenido, linea)
				end
			end
			--写入文本
			writeLines(configPath, contenido)	
		end
	end
	
	ProgressDialog(NOW_EXECUTING, "", 50, nil)
 
	--删除旧插件
    if sel == 1 then
    	deletePath(storagemgrDstPath)
    	deletePath(storagemgrConfigPath)
    	deletePath(storagemgrLogPath)    
    elseif sel == 2 then
	   deletePath(gamesdDstPath)
    elseif sel == 3 then
	   deletePath(usbmcDstPath)
    end

	unlock_home_key()
	ProgressDialog(NOW_EXECUTING, "", 100, nil)
	dismissDialog()

end

----------------刷新游戏气泡----------------
function refresh_psv_game()

	if ProgressDialog(NOW_REFRESHLLING, "", 0, CANCEL) == 0 then
		dismissDialog()
		return
	end
		 
	local uxAppPath = "ux0:/app"
	if not checkFolderExist(uxAppPath) then
		MessageDialog(TIPS, REFRESH_GAME_NO_UXAPP, BACK)
		return
	end

	local gameList = game.list(3)
	local fileList = files.listdirs(uxAppPath)
	local installList = {}
	for i = 1, #fileList do
		while true do
			local filePath = fileList[i].path
			local sfoPath = filePath.."/sce_sys/param.sfo"
			if not checkFileExist(sfoPath) then
				break
			end
			local gameInfo = game.info(sfoPath)
			if not gameInfo then
				break
			end
			local gameId = gameInfo.TITLE_ID
			if not gameId then
				break
			end
			local gameExist = false
			for k = 1, #gameList do
				if gameList[k].id == gameId then
					gameExist = true
					break
				end
			end
			if gameExist and game.rif(gameId) then
				break
			end
			table.insert(installList, fileList[i])
			break
		end
	end

	local install_counts = #installList
	if install_counts < 1 then
		MessageDialog(TIPS, REFRESH_GAME_NO_NEED_REFRESH, BACK)
		return		
	end
	lock_home_key()

	local completed_counts = 0
	local failed_counts = 0
	local percent = nil
	for i = 1, install_counts do
		if not percent then
			percent = 0
		end
		if ProgressDialog(NOW_REFRESHLLING, installList[i].name, percent, CANCEL) == 0 then
			break
		end
		local ret = install_game_dir(installList[i].path)
		if ret == 1 then
			completed_counts += 1
		else
			failed_counts += 1
		end
		percent = math.floor((i/install_counts)*100)
		if ProgressDialog(NOW_REFRESHLLING, installList[i].name, percent, CANCEL) == 0 then
			break
		end		
	end
  
	unlock_home_key()
	dismissDialog()

	MessageDialog(TIPS, string.format(REFRESH_GAME_COMPLETED, completed_counts, failed_counts), BACK)

end

----------------psv游戏管理----------------
function psvgameManagerInit()

  dofile("scripts/psvgamemanager/psvgamemanager.lua")

end

----------------文件管理器----------------
function explorerInit()

  dofile("scripts/explorer/explorer.lua")

end

----------------音乐播放器----------------
function musicPlayerInit()

  dofile("scripts/musicplayer/musicplayer.lua")

end

----------------常用插件大全----------------
function pluginManagerInit()

  dofile("scripts/pluginmanager/pluginmanager.lua")

end

----------------TF卡套卡插件----------------
function gamesdToolInit()

    --tf卡和usb插件
    local entries = {
        {text = INSTALL_GAMESD_UMA, enable = true},
        {text = INSTALL_GAMESD_UX, enable = true},
        {text = UNINSTALL_GAMESD, enable = true},
        {text = GAMESD_ABOUT, enable = true},
    }
  
	local sel = ItemDialog(PLEASE_SELECT, entries, CANCEL, POSITIVE)
	if sel == 1 or sel == 2 then
		local install_mode = 1
		local install_sel = 1
		if sel == 1 then
			install_sel = 1
		elseif sel == 2 then
			install_sel = 2
		end
		local state = MessageDialog(TIPS, string.format(INSTALL_GAMESD_READY, entries[sel].text), CANCEL, POSITIVE)
		if state == 1 then 
			local ret = install_gamesd(install_mode, install_sel)
			if ret < 0 then
				MessageDialog(TIPS, NO_CONFIG, BACK)
			else
				local state = MessageDialog(TIPS, string.format(INSTALL_GAMESD_COMPLETED, entries[sel].text), CANCEL, POSITIVE)
				if state == 1 then
					WaitDialog(WAIT_EXECUTING)
					os.delay(200)
					power.restart()
				end
			end
		end

	elseif sel == 3 then
		local state = MessageDialog(TIPS, UNINSTALL_GAMESD_READY, CANCEL, POSITIVE)
		if state == 1 then
			uninstall_gamesd(2)
			local state = MessageDialog(TIPS, UNINSTALL_GAMESD_COMPLETED, CANCEL, POSITIVE)
			if state == 1 then
				WaitDialog(WAIT_EXECUTING)
				os.delay(200)
				power.restart()
			end
		end
		
	elseif sel == 4 then
		MessageDialog(GAMESD_ABOUT, GAMESD_ABOUT_MESSAGE, BACK)
	
	end

end

----------------刷新游戏气泡----------------
function refreshGameInit()

	local state = MessageDialog(TIPS, REFRESH_GAME_READY, CANCEL, POSITIVE)
	if state == 1 then
		refresh_psv_game()
	end 

end

----------------查看设备信息----------------
function deviceViewerInit()

  dofile("scripts/deviceviewer/deviceviewer.lua")

end

----------------备份还原账号----------------
function accountManagerInit()

  dofile("scripts/accountmanager/accountmanager.lua")

end

----------------重构数据库----------------
function rebuildDatabaseInit()

	local state = MessageDialog(TIPS, REBUILDDB_READY, CANCEL, POSITIVE)
	if state == 1 then
		WaitDialog(WAIT_EXECUTING)
		rebuilddb()
		local state = MessageDialog(TIPS, REBUILDDB_COMPLETED, CANCEL, POSITIVE)
		if state == 1 then
			WaitDialog(WAIT_EXECUTING)
			os.delay(200)
			power.restart()
		end
	end

end

----------------解除记忆卡关联----------------
function relinkMcInit()

	local state = MessageDialog(TIPS, RELINK_MC_READY, CANCEL, POSITIVE)
	if state == 1 then
		WaitDialog(WAIT_EXECUTING)
		relink_mc()
		MessageDialog(TIPS, RELINK_MC_COMPLETED, BACK)
	end

end

----------------重启设备----------------
function rebootInit()

		local state = MessageDialog(TIPS, REBOOT_READY, CANCEL, POSITIVE)
		if state == 1 then
			WaitDialog(WAIT_EXECUTING)
			os.delay(200)
			power.restart()
		end

end

----------------更多功能----------------
function menuMoreInit()

	dofile("scripts/menumore/menumore.lua")

end

--------------检查软件更新-------------------------------
function checkUpdateInit()
	
	if not wlan.isconnected() then
		MessageDialog(TIPS, CHECK_UPDATER_NO_WLAN, BACK)
		return
	end

    if CHECK_UPDATER_FAILED then
        checkUpdater()
    end
	
    while true do
        while CHECKING_UPDATER do
            local state = ProgressDialog(NOW_CHECKING, CHECK_UPDATER_UPDATE_VERSION_INFO, 0, CANCEL)
            if state == 0 then
                return
            end
    	end

        if not CHECK_UPDATER_FAILED then
            break
        end
		local state = MessageDialog(TIPS, CHECK_UPDATER_GET_VERSION_INFO_ERROR, BACK, nil, RETRY)
        if state == 0 then
            return
        elseif state == 2 then
            checkUpdater()
        end
    end
    
    if not HAVE_UPDATER then
		MessageDialog(TIPS, CHECK_UPDATER_CURRENT_IS_LASTRELEASE, BACK)
		return
    end    
    
	local version_major = (UPDATER_VERSION >> 24) & 0xFF
	local version_minor = (UPDATER_VERSION >> 16) & 0xFF
	local version_revision = (UPDATER_VERSION >> 8) & 0xFF
	local version_str = string.format("%x.%02x", version_major, version_minor)
	if version_revision > 0 then
		version_str = version_str..string.format(".%x", version_revision)
	end
	local state = MessageDialog(TIPS, string.format(CHECK_UPDATER_FIND_UPDATE_VERSION, version_str), CANCEL, POSITIVE)
	if state ~= 1 then
		return
	end
	
	DOWNLOAD_FILE_NAME = APP_NAME.."_v"..version_str..".vpk"
	ProgressDialog(NOW_DOWNLOADING, DOWNLOAD_FILE_NAME, 0, CANCEL, nil)
	lock_home_key()
	
	local path = "ux0:/data/"..DOWNLOAD_FILE_NAME
	local ret = http.download(UPDATER_URL, path)
	dismissDialog()
	if not ret then
		files.delete(path)
		unlock_home_key()
		MessageDialog(TIPS, CHECK_UPDATER_DOWNLOAD_UPDATER_FAILED, BACK)
		return		
	end
	if DOWNLOAD_CANCEL then
		files.delete(path)
		unlock_home_key()
		return
	end
	local installDirPath = stripExtension(path)
	ProgressDialog(NOW_EXTRACTING, nil, 0, CANCEL, nil)
	deletePath(installDirPath)
	ret = files.extract(path, installDirPath)
	if ret == 0 then
		deletePath(installDirPath)
		unlock_home_key()
		dismissDialog()
		return
	elseif ret ~= 1 then
		deletePath(installDirPath)
		unlock_home_key()
		MessageDialog(TIPS, CHECK_UPDATER_EXTRACT_UPDATER_FAILED, BACK)
		return
	end
	ProgressDialog(NOW_INSTALLING, CHECK_UPDATER_TEMP_APP, 0, nil)
	files.mkdir("ux0:/data/updatepkg")
	files.copy("eboot.bin","ux0:/data/updatepkg/")
	files.copy("git/updater/script.lua","ux0:/data/updatepkg/")
	files.copy("git/updater/update.png","ux0:/data/updatepkg/")
	files.copy("git/updater/param.sfo","ux0:/data/updatepkg/sce_sys/")
	ProgressDialog(NOW_INSTALLING, CHECK_UPDATER_TEMP_APP, 50, nil)
	ret = game.installdir("ux0:/data/updatepkg")
	deletePath("ux0:/data/updatepkg")
	if ret ~= 1 then
		unlock_home_key()
		MessageDialog(TIPS, CHECK_UPDATER_INSTALL_TEMP_APP_FAILED, BACK)
		return				
	end
	ProgressDialog(NOW_INSTALLING, CHECK_UPDATER_TEMP_APP, 100, nil)
	game.launch(string.format("ONEUPDATE&%s&%s", os.titleid(), installDirPath))
	
	unlock_home_key()

end

----------------关于----------------
function aboutInit()

	local state = MessageDialog(ABOUT, string.format(ABOUT_TXT, APP_VERSION_STR, APP_BUILD_DATE), BACK, nil, UPDATE_LOG)
	if state == 2 then
		TEXTEDITOR_FILE_PATH = "resources/updatelog.txt"
		TEXTEDITOR_FILE_NAME = UPDATE_LOG    
		TEXTEDITOR_OPEN_MODE = __READ
		dofile("scripts/texteditor/texteditor.lua")
	end

end


